<template>
  <a-card>
    <a-row :gutter="16">
      <a-col :span="6">
        <a-card title="权限分配">
          <a-switch @change="onSwitch" checked-children="展开" size="small" un-checked-children="收缩" />
          <a-divider type="vertical" />
          <a-button
            v-permission="{ meta: $route.meta, permissionCode: 'BIND_PERM' }"
            icon="api"
            shape="round"
            type="primary"
            size="small"
            :disabled="!roleId"
            :loading="binding"
            @click="saveRolePerms"
            >绑定</a-button
          >
          <a-form layout="horizontal" :form="form">
            <a-form-item label="拥有权限">
              <a-tree checkable default-expand-all :expanded-keys="expandedKeys" :selectable="false" v-model="checkedKeys" :tree-data="permTreeData" @expand="onExpand" />
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
      <a-col :span="18">
        <div class="table-operations">
          <a-button v-permission="{ meta: $route.meta, permissionCode: 'ADD' }" type="primary" @click="onAdd">新建</a-button>
        </div>
        <a-table
          bordered
          size="middle"
          :loading="loading"
          :columns="columns"
          :rowKey="(record) => record.id"
          :dataSource="data"
          @change="handleTableChange"
          :pagination="pagination"
          :row-selection="{ type: 'radio', selectedRowKeys: selectedRowKeys, onChange: onRowSelectChange }"
        >
          <!-- table-row-operatiin -->
          <template v-slot:operation="record">
            <div class="table-row-operations">
              <a v-permission="{ meta: $route.meta, permissionCode: 'UPDATE' }" href="javascript:;" @click="onEdit(record)">修改</a>
              <a-popconfirm v-permission="{ meta: $route.meta, permissionCode: 'DELETE' }" title="Sure to delete?" @confirm="() => onDelete(record)">
                <a href="javascript:;">删除</a>
              </a-popconfirm>
            </div>
          </template>
        </a-table>
      </a-col>
    </a-row>
    <role-form ref="form" :is-add="isAdd" @refreshTable="init" />
  </a-card>
</template>

<script>
const columns = [
  {
    title: '角色名',
    dataIndex: 'name',
    sorter: false
  },
  {
    title: '备注',
    dataIndex: 'remark',
    sorter: false
  },
  {
    title: '操作',
    key: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]

import initData from '@/mixins/initData'
import permission from '@/directive/permission' // 权限判断指令
import RoleForm from './form'
import { get, del, getPermissionTree, getPermsByRoleId, updatePerms } from '@/api/role'

export default {
  name: 'Role',
  components: { RoleForm },
  directives: { permission },
  mixins: [initData],
  data() {
    return {
      columns,
      checkedKeys: [],
      permTreeData: [],
      expandedKeys: [],
      roleId: null,
      selectedRowKeys: [],
      binding: false,
      // changeType: '',
      form: this.$form.createForm(this, { name: 'rolePermRel' })
    }
  },
  created() {
    this.$nextTick(() => {
      this.init()
      this.loadPermTreeData()
    })
  },
  watch: {},
  computed: {},
  methods: {
    beforeInit() {
      this.selectedRowKeys = []
      this.roleId = null
      // ajax query
      this.url = 'oauth/role/page'
      this.params = {
        current: this.pagination.current,
        size: this.pagination.pageSize,
        sort: this.sort,
        ...this.query
      }
      return true
    },
    async loadPermTreeData() {
      const res = await getPermissionTree()
      this.permTreeData = res.data
    },
    onExpand(expandedKeys, data) {
      this.expandedKeys = [...expandedKeys]
    },
    onSwitch(checked) {
      if (!checked) {
        this.expandedKeys = []
      } else {
        const keys = []
        const treeKeyList = (data) => {
          for (let i = 0; i < data.length; i++) {
            const node = data[i]
            keys.push(node.key)
            if (node.children) {
              treeKeyList(node.children)
            }
          }
        }
        treeKeyList(this.permTreeData)
        this.expandedKeys = keys
      }
    },
    onAdd() {
      this.isAdd = true
      const _this = this.$refs['form']
      _this.visible = true
    },
    async onEdit(record) {
      let res = await get(record.id)
      this.isAdd = false
      const _this = this.$refs['form']
      _this.form = { ...res.data }
      _this.visible = true
    },
    async onDelete(record) {
      const key = 'delUser'
      try {
        this.$message.loading({ content: '正在删除...', key })
        let res = await del(record.id)
        this.$message.success({ content: '删除成功!', key, duration: 1 })
        this.init()
      } catch (err) {
        this.$message.error({ content: '删除失败', key })
        console.error(err.message)
      }
    },
    async onRowSelectChange(selectedRowKeys) {
      const key = 'getPermsByRoleId'
      this.selectedRowKeys = selectedRowKeys
      const roleId = selectedRowKeys[0]
      try {
        this.$message.loading({ content: '正在加载...', key })

        const res = await getPermsByRoleId({ roleId })
        this.checkedKeys = res.data
        // this.changeType = 'role'
        this.roleId = roleId

        this.$message.success({ content: '加载成功!', key, duration: 2 })
      } catch (err) {
        console.error(err.message)
      }
    },
    async saveRolePerms() {
      const key = 'saveRolePerms'
      try {
        if (!this.roleId) {
          this.$message.warn({ content: '请先选择一个角色!', key, duration: 2 })
          return
        }
        this.binding = true
        this.$message.loading({ content: '正在保存...', key })
        await updatePerms({ roleId: this.roleId, permIds: this.checkedKeys })
        this.binding = false
        this.$message.success({ content: '保存成功!', key, duration: 2 })
      } catch (err) {
        console.error(err.message)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.long-hide-text {
  overflow: hidden; //超出隐藏
  text-overflow: ellipsis; // 省略号
  white-space: nowrap; //不换行
}
</style>
